"""
订单管理API端点
"""
from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session

from app.database import get_db
from app.models.order import Order
from app.schemas.order import OrderCreate, OrderUpdate, OrderResponse
from app.api.deps import get_current_active_user

router = APIRouter()


@router.get("/")
def get_orders(
    db: Session = Depends(get_db),
    page: int = 1,
    size: int = 20,
    order_no: str = None,
    student_id: int = None,
    course_id: int = None,
    status: str = None,
    # current_user: Any = Depends(get_current_active_user)  # 临时移除认证要求
) -> Any:
    """
    获取订单列表
    """
    query = db.query(Order)
    
    # 添加搜索条件
    if order_no:
        query = query.filter(Order.order_no.contains(order_no))
    if student_id:
        query = query.filter(Order.student_id == student_id)
    if course_id:
        query = query.filter(Order.course_id == course_id)
    if status:
        query = query.filter(Order.status == status)
    
    # 计算总数
    total = query.count()
    
    # 分页
    skip = (page - 1) * size
    orders = query.offset(skip).limit(size).all()
    
    # 将SQLAlchemy模型转换为字典
    orders_data = []
    for order in orders:
        order_dict = {
            "id": order.id,
            "order_no": order.order_no,
            "student_id": order.student_id,
            "course_id": order.course_id,
            "payment_method": order.payment_method,
            "registration_type": order.registration_type,
            "should_pay_amount": float(order.should_pay_amount) if order.should_pay_amount else 0.0,
            "actual_pay_amount": float(order.actual_pay_amount) if order.actual_pay_amount else 0.0,
            "order_date": order.order_date.isoformat() if order.order_date else None,
            "sales_employee_id": order.sales_employee_id,
            "reception_employee_id": order.reception_employee_id,
            "customer_service_employee_id": order.customer_service_employee_id,
            "performance_source": order.performance_source,
            "status": order.status,
            "created_at": order.created_at.isoformat() if order.created_at else None,
            "updated_at": order.updated_at.isoformat() if order.updated_at else None
        }
        orders_data.append(order_dict)
    
    return {
        "items": orders_data,
        "total": total,
        "page": page,
        "size": size
    }


@router.get("/{order_id}", response_model=OrderResponse)
def get_order(
    order_id: int,
    db: Session = Depends(get_db),
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    获取单个订单信息
    """
    order = db.query(Order).filter(Order.id == order_id).first()
    if not order:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="订单不存在"
        )
    return order


@router.post("/", response_model=OrderResponse)
def create_order(
    *,
    db: Session = Depends(get_db),
    order_in: OrderCreate,
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    创建新订单
    """
    # 检查订单号是否已存在
    existing_order = db.query(Order).filter(
        Order.order_no == order_in.order_no
    ).first()
    if existing_order:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="订单号已存在"
        )
    
    order = Order(**order_in.dict())
    db.add(order)
    db.commit()
    db.refresh(order)
    return order


@router.put("/{order_id}", response_model=OrderResponse)
def update_order(
    *,
    db: Session = Depends(get_db),
    order_id: int,
    order_in: OrderUpdate,
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    更新订单信息
    """
    order = db.query(Order).filter(Order.id == order_id).first()
    if not order:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="订单不存在"
        )
    
    update_data = order_in.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(order, field, value)
    
    db.add(order)
    db.commit()
    db.refresh(order)
    return order


@router.delete("/{order_id}")
def delete_order(
    *,
    db: Session = Depends(get_db),
    order_id: int,
    current_user: Any = Depends(get_current_active_user)
) -> Any:
    """
    删除订单
    """
    order = db.query(Order).filter(Order.id == order_id).first()
    if not order:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="订单不存在"
        )
    
    db.delete(order)
    db.commit()
    return {"message": "订单删除成功"}
